package com.example.mysecondapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RateListActivity extends AppCompatActivity implements Runnable, 
        AdapterView.OnItemClickListener
        , AdapterView.OnItemLongClickListener
{

    private static final String TAG = "RateListActivity";
    Handler handler = new Handler();
//    GridView listView;
    ListView listView;
    List<HashMap<String,String>> listItem;
    SimpleAdapter adapter;
    SQLiteDatabase sqLiteDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate_list);

        DBHelper dbHelper = new DBHelper(this);
        sqLiteDatabase = dbHelper.getWritableDatabase();//建立数据库连接

        //先从数据库中获取日期,判断是否超过一天,超过则爬数据进入数据库,读取显示都从数据库中获取数据
        Cursor updateTimeSql = sqLiteDatabase.query("update_time", new String[]{"updateTime"}, null, null, null, null, null);
        //String updateTime = updateTimeSql.getString(updateTimeSql.getColumnIndexOrThrow("updateTime"));
        //Log.i(TAG, "onCreate: updateTime"+ updateTime);
        if (!updateTimeSql.moveToFirst()){//若为空则将今天日期放入,
            Date date = new Date();
            long time = date.getTime()/(1000*3600*24)*(1000*3600*24);
            ContentValues contentValues = new ContentValues();
            contentValues.put("updateTime",time);
            sqLiteDatabase.insert("update_time",null,contentValues);
            Log.i(TAG, "onCreate: 日期初始化");
        }
        else {
            long updateTime =Long.parseLong(updateTimeSql.getString(updateTimeSql.getColumnIndexOrThrow("updateTime")));
            Log.i(TAG, "onCreate: updateTime"+ updateTime);
            Date now = new Date();
            if(((now.getTime()- updateTime)/1000/60/60/24)>=1){//如果超过一天未更新,则更新
                Thread thread = new Thread(this);
                thread.start();

                try {//等待爬虫完成
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        }




//        Thread thread = new Thread(this);
//        thread.start();
//        handler = new Handler(Looper.myLooper()){
//            @Override
//            public void handleMessage(@NonNull Message msg) {
//                if(msg.what == 0){
//                    listItem =(List<HashMap<String,String>>) msg.obj;
//                    adapter = new SimpleAdapter(RateListActivity.this,
//                            listItem,
//                            R.layout.list_item,
//                            new String[]{"title","detail"},
//                            new int[]{R.id.itemTitle,R.id.itemDetail});
//
////                    listView = findViewById(R.id.gridview_rate);
//                    listView = findViewById(R.id.listview_rate);
//                    listView.setAdapter(adapter);
//                    listView.setEmptyView(findViewById(R.id.no_data));
//                    listView.setOnItemClickListener(RateListActivity.this);
//                    listView.setOnItemLongClickListener(RateListActivity.this);
//                }
//                super.handleMessage(msg);
//            }
//        };


    }

    @Override
    public void run() {
        Document doc = null;
        try {
            for(int i = 0;i<10;i++){//一共有10页,所以10次循环
                if(i==0)
                    doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/index.html").get();
                else
                    doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/index_"+i+".html").get();
                Elements tables = doc.getElementsByTag("tbody").get(1).getElementsByTag("tr");
                tables.remove(0);
                for (Element table : tables) {
                    String name = table.getElementsByTag("td").get(0).text();
                    String val =table.getElementsByTag("td").get(5).text();
                    HashMap<String,String> map = new HashMap<>();
                    map.put("title",name);
                    map.put("detail",val);
                    listItem.add(map);
                }
            }
            Message msg = handler.obtainMessage(0);
            msg.obj = listItem;
            handler.sendMessage(msg);
        }
        catch (Exception e){
            e.printStackTrace();
            Log.i(TAG, "run: wrong");
        }
//        Document doc = null;
//        List<HashMap<String,String>> listItem = new ArrayList<>();
//        try {
//            for(int i = 0;i<10;i++){//一共有10页,所以10次循环
//                if(i==0)
//                    doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/index.html").get();
//                else
//                    doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/index_"+i+".html").get();
//                Elements tables = doc.getElementsByTag("tbody").get(1).getElementsByTag("tr");
//                tables.remove(0);
//                for (Element table : tables) {
//                    String name = table.getElementsByTag("td").get(0).text();
//                    String val =table.getElementsByTag("td").get(5).text();
//                    HashMap<String,String> map = new HashMap<>();
//                    map.put("title",name);
//                    map.put("detail",val);
//                    listItem.add(map);
//                }
//            }
//            Message msg = handler.obtainMessage(0);
//            msg.obj = listItem;
//            handler.sendMessage(msg);
//        }
//        catch (Exception e){
//            e.printStackTrace();
//            Log.i(TAG, "run: wrong");
//        }

    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object itemAtPosition = listView.getItemAtPosition(position);
        HashMap<String,String> map = (HashMap<String,String>) itemAtPosition;
        String title = map.get("title");
        String detail = map.get("detail");
        Log.i(TAG, "onItemClick: "+title + "\n" + detail);

        Intent intent = new Intent(this,RateList2Activity.class);
        intent.putExtra("title",title);
        intent.putExtra("detail",detail);
        int requestCode = 1000;
        startActivityForResult(intent,requestCode);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i(TAG, "onItemLongClick: 长按操作");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("是否删除当前数据项")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(TAG, "onClick: 对话框事件处理");
                        listItem.remove(position);
                        adapter.notifyDataSetChanged();
                    }
                }).setNegativeButton("否",null);
        builder.create().show();
        return true;//返回false会触发单击,返回true不会触发单击
    }
}